﻿using DinletBilsin.WebService.Models;
using DinletBilsin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace DinletBilsin.WebService.Controllers
{
    public class SearchMusicController : ApiController
    {

        public Task<IEnumerable<string>> Post()
        {
            if (Request.Content.IsMimeMultipartContent())
            {
                string fullPath = HttpContext.Current.Server.MapPath("~/App_Data");
                DBilsinStream streamProvider = new DBilsinStream(fullPath);
                KeyValuePair<string, IEnumerable<string>> authorization = Request.Headers.ToList().Where(s => s.Key == "Authorization").FirstOrDefault();
                KeyValuePair<string, IEnumerable<string>> size = Request.Headers.ToList().Where(s => s.Key == "Size").FirstOrDefault();    
              
                if (authorization.Value == null || size.Value == null)
                    throw new HttpResponseException(HttpStatusCode.Forbidden);

                var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
                {
                    if (t.IsFaulted || t.IsCanceled)
                        throw new HttpResponseException(HttpStatusCode.InternalServerError);

                    string ss = ComputeHash(size.Value.ToList()[0], "XYZSecurity");

                    if (!ss.Equals(authorization.Value.ToList()[0]))
                        throw new HttpResponseException(HttpStatusCode.Forbidden);
                    var fileInfo = streamProvider.FileData.Select(i =>
                    {
                        Util.cacheHashMap = HttpRuntime.Cache["hashMap"] as Dictionary<long, List<FingerPrint>>;                      
                        Util.cacheSongNames = HttpRuntime.Cache["songNames"] as List<string>;
                        Util.DataBasePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"),Util.DataBasePath);
                        String str = DinletBilsinCore.ReturnResult(i.LocalFileName,(bool) HttpRuntime.Cache["CacheLoaded"],null );
                        return str;
                    });
                    

                    return fileInfo;
                });
                return task;
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Invalid Request!"));
            }
        }

        private string ComputeHash(string hashedPassword, string message)
        {
            byte[] secretKey = Encoding.UTF8.GetBytes(hashedPassword);
            HMACSHA256 hmac = new HMACSHA256(secretKey);
            hmac.Initialize();
            byte[] bytes = Encoding.UTF8.GetBytes(message);
            byte[] rawHmac = hmac.ComputeHash(bytes);
           
            return Convert.ToBase64String(rawHmac);
           
        }
    }
    public class SearchMusicAndroidController : ApiController
    {
        /// <summary>
        /// Android uygulaması upload yaptığında burası çalışır.
        /// </summary>
        /// <returns></returns>
        public String Post()
        {

            try
            {
                string fileName = "\\androidData.byte";
                string fullPath = HttpContext.Current.Server.MapPath("~/App_Data") + fileName;
                DBilsinStream streamProvider = new DBilsinStream(fullPath);

                byte[] data = Request.Content.ReadAsByteArrayAsync().Result;
                File.WriteAllBytes(fullPath, data);
                Util.cacheHashMap = HttpRuntime.Cache["hashMap"] as Dictionary<long, List<FingerPrint>>;             
                Util.cacheSongNames = HttpRuntime.Cache["songNames"] as List<string>;
                Util.DataBasePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), Util.DataBasePath);
                String str = DinletBilsinCore.ReturnResult(fullPath, (bool)HttpRuntime.Cache["CacheLoaded"], null,true);
                return str;  
            }
            catch (Exception e)
            {

                return "Hata Oluştu: \n " + e.Message;

            }
                                        
        }
    }
    public class SearchMusicRawController : ApiController
    {

        public Task<IEnumerable<string>> Post()
        {
            if (Request.Content.IsMimeMultipartContent())
            {
                string fullPath = HttpContext.Current.Server.MapPath("~/App_Data");
                DBilsinStream streamProvider = new DBilsinStream(fullPath);
                KeyValuePair<string, IEnumerable<string>> authorization = Request.Headers.ToList().Where(s => s.Key == "Authorization").FirstOrDefault();
                KeyValuePair<string, IEnumerable<string>> size = Request.Headers.ToList().Where(s => s.Key == "Size").FirstOrDefault();

                if (authorization.Value == null || size.Value == null)
                    throw new HttpResponseException(HttpStatusCode.Forbidden);

                var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
                {
                    if (t.IsFaulted || t.IsCanceled)
                        throw new HttpResponseException(HttpStatusCode.InternalServerError);

                    string ss = ComputeHash(size.Value.ToList()[0], "XYZSecurity");

                    if (!ss.Equals(authorization.Value.ToList()[0]))
                        throw new HttpResponseException(HttpStatusCode.Forbidden);
                    var fileInfo = streamProvider.FileData.Select(i =>
                    {
                        Util.cacheHashMap = HttpRuntime.Cache["hashMap"] as Dictionary<long, List<FingerPrint>>;                        
                        Util.cacheSongNames = HttpRuntime.Cache["songNames"] as List<string>;
                        Util.DataBasePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), Util.DataBasePath);
                        String str = DinletBilsinCore.ReturnResult(i.LocalFileName, (bool)HttpRuntime.Cache["CacheLoaded"], null, true);
                        return str;
                    });


                    return fileInfo;
                });
                return task;
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Invalid Request!"));
            }
        }

        private string ComputeHash(string hashedPassword, string message)
        {
            byte[] secretKey = Encoding.UTF8.GetBytes(hashedPassword);
            HMACSHA256 hmac = new HMACSHA256(secretKey);
            hmac.Initialize();
            byte[] bytes = Encoding.UTF8.GetBytes(message);
            byte[] rawHmac = hmac.ComputeHash(bytes);

            return Convert.ToBase64String(rawHmac);

        }
    }
}
